from fastapi import APIRouter, HTTPException, Query, Depends
from typing import List, Optional
from pydantic import BaseModel, Field
from tortoise.exceptions import DoesNotExist
from models.m import User
import jwt
from datetime import datetime, timedelta
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials

users_router = APIRouter(prefix="/users", tags=["用户"])

# JWT配置
SECRET_KEY = "your-secret-key-please-change-in-production"
ALGORITHM = "HS256"

# JWT安全模式
security = HTTPBearer()

class LoginIn(BaseModel):
    account: str  # 对应User表的name字段（相当于手机号）
    password: str  # 对应User表的pwd字段（密码）

class LoginOut(BaseModel):
    code: int
    message: str
    data: dict

class RegisterIn(BaseModel):
    account: str  # 对应User表的name字段（相当于手机号）
    password: str  # 对应User表的pwd字段（密码）

class RegisterOut(BaseModel):
    code: int
    message: str
    data: dict


@users_router.post("/register", response_model=RegisterOut)
async def register(payload: RegisterIn):
    """
    用户注册接口
    - account字段对应User表的name字段（相当于手机号）
    - password字段对应User表的pwd字段（密码）
    """
    # 验证账号和密码不能为空
    if not payload.account or not payload.password:
        raise HTTPException(
            status_code=400,
            detail={"code": 400, "message": "账号或密码不能为空"}
        )
    
    # 验证账号长度
    if len(payload.account) < 6 or len(payload.account) > 20:
        raise HTTPException(
            status_code=400,
            detail={"code": 400, "message": "账号长度应在6-20位之间"}
        )
    
    # 验证密码长度
    if len(payload.password) < 6:
        raise HTTPException(
            status_code=400,
            detail={"code": 400, "message": "密码长度至少6位"}
        )
    
    try:
        # 检查账号是否已存在
        existing_user = await User.filter(name=payload.account).first()
        if existing_user:
            raise HTTPException(
                status_code=400,
                detail={"code": 400, "message": "账号已存在，请直接登录"}
            )
        
        # 创建新用户（role_id默认为1，表示普通用户）
        new_user = await User.create(
            name=payload.account,
            pwd=payload.password,
            role_id=1  # 默认角色ID为1（普通用户）
        )
        
        return {
            "code": 200,
            "message": "注册成功",
            "data": {
                "userid": new_user.id,
                "account": new_user.name
            }
        }
        
    except HTTPException:
        raise
    except Exception as e:
        # 打印详细错误信息
        import traceback
        error_trace = traceback.format_exc()
        print(f"注册失败详细错误: {error_trace}")
        print(f"错误类型: {type(e).__name__}")
        print(f"错误信息: {str(e)}")
        
        error_msg = str(e)
        if "NOT NULL" in error_msg or "null" in error_msg.lower():
            error_msg = "数据库字段缺失或不允许为空，请检查数据库表结构"
        elif "duplicate" in error_msg.lower() or "unique" in error_msg.lower():
            error_msg = "账号已存在，请直接登录"
        
        raise HTTPException(
            status_code=500,
            detail={"code": 500, "message": f"注册失败: {error_msg}"}
        )


@users_router.post("/login", response_model=LoginOut)
async def login(payload: LoginIn):
    """
    用户登录接口
    - account字段对应User表的name字段（相当于手机号）
    - password字段对应User表的pwd字段（密码）
    """
    # 验证账号和密码不能为空
    if not payload.account or not payload.password:
        raise HTTPException(
            status_code=400, 
            detail={"code": 400, "message": "账号或密码不能为空"}
        )
    
    try:
        # 根据name字段查询用户（name相当于手机号）
        user = await User.filter(name=payload.account).first()
        
        # 用户不存在
        if not user:
            raise HTTPException(
                status_code=400,
                detail={"code": 400, "message": "账号不存在"}
            )
        
        # 验证密码
        if user.pwd != payload.password:
            raise HTTPException(
                status_code=400,
                detail={"code": 400, "message": "密码错误"}
            )
        
        # 密码正确，生成JWT token
        expire = datetime.utcnow() + timedelta(days=7)
        token_data = {
            "sub": str(user.id),
            "user_id": user.id,
            "name": user.name,
            "exp": expire
        }
        token = jwt.encode(token_data, SECRET_KEY, algorithm=ALGORITHM)
        
        return {
            "code": 200,
            "message": "登录成功",
            "data": {
                "token": token,
                "userid": user.id
            }
        }
        
    except HTTPException:
        # 重新抛出HTTPException
        raise
    except Exception as e:
        # 其他异常
        raise HTTPException(
            status_code=500,
            detail={"code": 500, "message": f"登录失败: {str(e)}"}
        )


@users_router.get("/reg/")
async def reg():
    return ["Rick", "Morty"]
